package com.xjscrm.console.service.customer.operatePlan.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.vo.msg.MsgData;
import com.xjscrm.common.vo.operatorplandevice.OperatorPlanDeviceRule;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.operatePlan.*;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.customer.operatePlan.GroupWelcomeService;
import com.xjscrm.console.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GroupWelcomeServiceImpl implements GroupWelcomeService {

    @Autowired
    private GroupWelcomeMapper groupWelcomeMapper;

    @Autowired
    private GroupWelcomeDeviceMapper groupWelcomeDeviceMapper;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private GroupWelcomeGroupMapper groupWelcomeGroupMapper;

    @Autowired
    private DeviceGroupRelationMapper deviceGroupRelationMapper;

    @Autowired
    private WwGroupMapper wwGroupMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addGroupWelcomePlan(GroupWelcomeDto groupWelcomeDto) {
        if(groupWelcomeDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupWelcomeDto.getMsgDataList()==null||groupWelcomeDto.getMsgDataList().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        GroupWelcome groupWelcome=new GroupWelcome();
        BeanUtil.copyProperties(groupWelcomeDto,groupWelcome);
        int time = DateUtil.getTime();
        Long sixDigitsNum = getSixDigitsNum();
        groupWelcome.setId(sixDigitsNum);
        groupWelcome.setCreateTime(time);
        groupWelcome.setUpdateTime(time);
        groupWelcome.setMsgDatas(JSONObject.toJSONString(groupWelcomeDto.getMsgDataList()));
        groupWelcomeMapper.insert(groupWelcome);

        //新增群欢迎语方案关联的群
        if(groupWelcomeDto.getGroupType()!=null&&groupWelcomeDto.getGroupType()==2&&groupWelcomeDto.getGroupWelcomeGroupDtoList()!=null&&!groupWelcomeDto.getGroupWelcomeGroupDtoList().isEmpty()){
            for (GroupWelcomeGroupDto groupWelcomeGroupDto:groupWelcomeDto.getGroupWelcomeGroupDtoList()) {
                GroupWelcomeGroup groupWelcomeGroup = new GroupWelcomeGroup();
                groupWelcomeGroup.setMerId(groupWelcome.getMerId());
                groupWelcomeGroup.setPlanId(groupWelcome.getId());
                groupWelcomeGroup.setDeviceUniqueId(groupWelcomeGroupDto.getDeviceUniqueId());
                groupWelcomeGroup.setGroupWxid(groupWelcomeGroupDto.getGroupWxid());
                groupWelcomeGroupMapper.add(groupWelcomeGroup);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGroupWelcomePlan(GroupWelcomeDto groupWelcomeDto) {
        if(groupWelcomeDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupWelcomeDto.getMsgDataList()==null||groupWelcomeDto.getMsgDataList().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(groupWelcomeDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        GroupWelcome groupWelcome= groupWelcomeMapper.getById(groupWelcomeDto.getId(),groupWelcomeDto.getMerId());
        if(groupWelcome==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该方案不存在");
        }

        //群欢迎语方案关联的群旧数据删除
        GroupWelcomeGroupQuery groupWelcomeGroupQuery=new GroupWelcomeGroupQuery();
        groupWelcomeGroupQuery.setMerId(groupWelcomeDto.getMerId());
        groupWelcomeGroupQuery.setPlanId(groupWelcomeDto.getId());
        List<GroupWelcomeGroupVo> groupWelcomeGroupVoList=groupWelcomeGroupMapper.getGroupWelcomeGroupList(groupWelcomeGroupQuery);
        if(groupWelcomeGroupVoList!=null&&!groupWelcomeGroupVoList.isEmpty()){
            groupWelcomeGroupVoList.forEach(it->groupWelcomeGroupMapper.delById(it.getId(),it.getMerId()));
        }

        //新增群欢迎语方案关联的群
        if(groupWelcomeDto.getGroupType()!=null&&groupWelcomeDto.getGroupType()==2&&groupWelcomeDto.getGroupWelcomeGroupDtoList()!=null&&!groupWelcomeDto.getGroupWelcomeGroupDtoList().isEmpty()){
            for (GroupWelcomeGroupDto groupWelcomeGroupDto:groupWelcomeDto.getGroupWelcomeGroupDtoList()) {
                GroupWelcomeGroup groupWelcomeGroup = new GroupWelcomeGroup();
                groupWelcomeGroup.setMerId(groupWelcome.getMerId());
                groupWelcomeGroup.setPlanId(groupWelcome.getId());
                groupWelcomeGroup.setDeviceUniqueId(groupWelcomeGroupDto.getDeviceUniqueId());
                groupWelcomeGroup.setGroupWxid(groupWelcomeGroupDto.getGroupWxid());
                groupWelcomeGroupMapper.add(groupWelcomeGroup);
            }
        }

        BeanUtil.copyProperties(groupWelcomeDto,groupWelcome);
        groupWelcome.setMsgDatas(JSONObject.toJSONString(groupWelcomeDto.getMsgDataList()));
        groupWelcomeMapper.update(groupWelcome);

    }


    @Override
    public Object getGroupWelcomePlanList(GroupWelcomeQuery groupWelcomeQuery) {

        if(groupWelcomeQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        String orderBy = OrderByUtil.getOrderBy(groupWelcomeQuery.getOrderByField(), groupWelcomeQuery.isAsc());
        PageHelper.startPage(groupWelcomeQuery.getCurrent(),groupWelcomeQuery.getSize(),orderBy);
        List<GroupWelcomeVo> groupWelcomeVoList=groupWelcomeMapper.getGroupWelcomePlanList(groupWelcomeQuery);

//        if(groupWelcomeVoList!=null&&!groupWelcomeVoList.isEmpty()){
//            for (GroupWelcomeVo groupWelcomeVo:groupWelcomeVoList) {
//                try {
//                    groupWelcomeVo.setMsgDataList(JSONObject.parseArray(groupWelcomeVo.getMsgDatas(), MsgData.class));
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//            }
//        }
        return new MyPageInfo<>(groupWelcomeVoList);
    }


    @Override
    public Object getGroupWelcomePlanDetail(GroupWelcomeDto groupWelcomeDto) {
        if(groupWelcomeDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupWelcomeDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        GroupWelcome groupWelcome = groupWelcomeMapper.getById(groupWelcomeDto.getId(), groupWelcomeDto.getMerId());
        if(groupWelcome==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该方案不存在");
        }

        GroupWelcomeVo groupWelcomeVo = new GroupWelcomeVo();
        BeanUtil.copyProperties(groupWelcome,groupWelcomeVo);
        groupWelcomeVo.setMsgDataList(JSONObject.parseArray(groupWelcome.getMsgDatas(),MsgData.class));


        GroupWelcomeGroupQuery groupWelcomeGroupQuery=new GroupWelcomeGroupQuery();
        groupWelcomeGroupQuery.setMerId(groupWelcome.getMerId());
        groupWelcomeGroupQuery.setPlanId(groupWelcome.getId());
        List<GroupWelcomeGroupVo> groupWelcomeGroupVoList=groupWelcomeGroupMapper.getGroupWelcomeGroupList(groupWelcomeGroupQuery);
        if(groupWelcomeGroupVoList!=null&&!groupWelcomeGroupVoList.isEmpty()){
            for (GroupWelcomeGroupVo groupWelcomeGroupVo:groupWelcomeGroupVoList) {
                try {
                    //获取机器人头像，昵称
                    WwDevice wwDevice = wwDeviceMapper.getById(groupWelcomeGroupVo.getDeviceUniqueId(), groupWelcomeGroupVo.getMerId());
                    if(wwDevice!=null){
                        groupWelcomeGroupVo.setDeviceName(wwDevice.getDeviceName());
                        groupWelcomeGroupVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                    }

                    //获取群
                    WwGroup wwGroup = wwGroupMapper.selectByGroupWxId(groupWelcomeGroupVo.getMerId(), groupWelcomeGroupVo.getDeviceUniqueId(), groupWelcomeGroupVo.getGroupWxid());
                    if(wwGroup!=null){
                        groupWelcomeGroupVo.setGroupName(wwGroup.getGroupName());
                        groupWelcomeGroupVo.setGroupId(wwGroup.getId());
                    }


                }catch (Exception e){
                    e.printStackTrace();
                }
            }



            groupWelcomeVo.setGroupWelcomeGroupVoList(groupWelcomeGroupVoList);
        }
        return groupWelcomeVo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delGroupWelcomePlan(GroupWelcomeDto groupWelcomeDto) {
        if(groupWelcomeDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupWelcomeDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        groupWelcomeMapper.delById(groupWelcomeDto.getId(),groupWelcomeDto.getMerId());

        //群欢迎语方案关联的群旧数据删除
        GroupWelcomeGroupQuery groupWelcomeGroupQuery=new GroupWelcomeGroupQuery();
        groupWelcomeGroupQuery.setMerId(groupWelcomeDto.getMerId());
        groupWelcomeGroupQuery.setPlanId(groupWelcomeDto.getId());
        List<GroupWelcomeGroupVo> groupWelcomeGroupVoList=groupWelcomeGroupMapper.getGroupWelcomeGroupList(groupWelcomeGroupQuery);
        if(groupWelcomeGroupVoList!=null&&!groupWelcomeGroupVoList.isEmpty()){
            groupWelcomeGroupVoList.forEach(it->groupWelcomeGroupMapper.delById(it.getId(),it.getMerId()));
        }

        //删除方案关联的机器人
        GroupWelcomeDeviceQuery groupWelcomeDeviceQuery=new GroupWelcomeDeviceQuery();
        groupWelcomeDeviceQuery.setPlanId(groupWelcomeDto.getId());
        groupWelcomeDeviceQuery.setMerId(groupWelcomeDto.getMerId());
        List<GroupWelcomeDeviceVo> groupWelcomeDeviceVoList=groupWelcomeDeviceMapper.getGroupWelcomeDeviceList(groupWelcomeDeviceQuery);
        if(groupWelcomeDeviceVoList!=null&&!groupWelcomeDeviceVoList.isEmpty()){
            groupWelcomeDeviceVoList.forEach(it->groupWelcomeDeviceMapper.delById(it.getId(),it.getMerId()));
        }

    }

    @Override
    public void addPlanDevice(GroupWelcomePlanDeviceDto groupWelcomePlanDeviceDto) {
        if(groupWelcomePlanDeviceDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupWelcomePlanDeviceDto.getPlanId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(groupWelcomePlanDeviceDto.getDeviceUniqueId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        GroupWelcome groupWelcome = groupWelcomeMapper.getById(groupWelcomePlanDeviceDto.getPlanId(), groupWelcomePlanDeviceDto.getMerId());
        if(groupWelcome==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该方案不存在");
        }

        WwDevice wwDevice = wwDeviceMapper.getById(groupWelcomePlanDeviceDto.getDeviceUniqueId(), groupWelcomePlanDeviceDto.getMerId());
        if(wwDevice==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        GroupWelcomeDevice groupWelcomeDevice=new GroupWelcomeDevice();
        groupWelcomeDevice.setMerId(groupWelcome.getMerId());
        groupWelcomeDevice.setPlanId(groupWelcome.getId());
        groupWelcomeDevice.setDeviceUniqueId(wwDevice.getId());
        groupWelcomeDevice.setDeviceId(wwDevice.getDeviceId());
        if(groupWelcomePlanDeviceDto.getRateMin()==null){
            groupWelcomeDevice.setRateMin(5);
        }else {
            groupWelcomeDevice.setRateMin(groupWelcomePlanDeviceDto.getRateMin());
        }
        if(groupWelcomePlanDeviceDto.getRateMax()==null){
            groupWelcomeDevice.setRateMax(10);
        }else {
            groupWelcomeDevice.setRateMax(groupWelcomePlanDeviceDto.getRateMax());
        }
        groupWelcomeDeviceMapper.add(groupWelcomeDevice);
    }


    @Override
    public void updatePlanDevice(GroupWelcomePlanDeviceDto groupWelcomePlanDeviceDto) {
        if(groupWelcomePlanDeviceDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupWelcomePlanDeviceDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if(groupWelcomePlanDeviceDto.getSleepRule()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        GroupWelcomeDevice groupWelcomeDevice=groupWelcomeDeviceMapper.getById(groupWelcomePlanDeviceDto.getId(),groupWelcomePlanDeviceDto.getMerId());

        if(groupWelcomeDevice==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"未找到该应用");
        }

        if(groupWelcomePlanDeviceDto.getRateMin()==null){
            groupWelcomeDevice.setRateMin(5);
        }else {
            groupWelcomeDevice.setRateMin(groupWelcomePlanDeviceDto.getRateMin());
        }
        if(groupWelcomePlanDeviceDto.getRateMax()==null){
            groupWelcomeDevice.setRateMax(10);
        }else {
            groupWelcomeDevice.setRateMax(groupWelcomePlanDeviceDto.getRateMax());
        }

        groupWelcomeDevice.setRule(JSONObject.toJSONString(groupWelcomePlanDeviceDto.getSleepRule()));
        groupWelcomeDeviceMapper.update(groupWelcomeDevice);

    }

    @Override
    public void delPlanDevice(GroupWelcomePlanDeviceDto groupWelcomePlanDeviceDto) {
        if(groupWelcomePlanDeviceDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupWelcomePlanDeviceDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        groupWelcomeDeviceMapper.delById(groupWelcomePlanDeviceDto.getId(),groupWelcomePlanDeviceDto.getMerId());

    }

    @Override
    public Object getPlanDeviceList(GroupWelcomeDeviceQuery groupWelcomeDeviceQuery) {
        if(groupWelcomeDeviceQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupWelcomeDeviceQuery.getPlanId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        List<Long> duviceUniqueId=new ArrayList<>();

        //关键词中有机器人ID或者机器人的name
        List<Long> getDeviceUniqueIds=new ArrayList<>();
        if(!StringUtils.isBlank(groupWelcomeDeviceQuery.getKeyword())){
            //机器人ID
            WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
            wwDeviceQuery.setMerId(groupWelcomeDeviceQuery.getMerId());
            wwDeviceQuery.setKeyword(groupWelcomeDeviceQuery.getKeyword());
            List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if(wwDeviceList!=null&&!wwDeviceList.isEmpty()){
                wwDeviceList.forEach(it->getDeviceUniqueIds.add(it.getId()));
            }
            if(getDeviceUniqueIds.isEmpty()){
                return  new MyPageInfo<>(null);
            }
        }

        //分组，获取分组中的机器人ID
        List<Long> groupDeviceUniqueIds=new ArrayList<>();
        if(groupWelcomeDeviceQuery.getGroupId()!=null){
            DeviceGroupRelationQuery deviceGroupRelationQuery=new DeviceGroupRelationQuery();
            deviceGroupRelationQuery.setMerId(groupWelcomeDeviceQuery.getMerId());
            deviceGroupRelationQuery.setGroupId(groupWelcomeDeviceQuery.getGroupId());
            List<DeviceGroupRelation> deviceGroupRelationList = deviceGroupRelationMapper.deviceGroupRelationList(deviceGroupRelationQuery);
            if(deviceGroupRelationList!=null&&!deviceGroupRelationList.isEmpty()){
                groupDeviceUniqueIds = deviceGroupRelationList.stream().map(DeviceGroupRelation::getDeviceUniqueId).distinct().collect(Collectors.toList());
            }
            if(groupDeviceUniqueIds.isEmpty()){
                return new MyPageInfo<>(null);
            }
        }

        if(!getDeviceUniqueIds.isEmpty()&&groupDeviceUniqueIds.isEmpty()){
            duviceUniqueId=getDeviceUniqueIds;
        }
        if(getDeviceUniqueIds.isEmpty()&&!groupDeviceUniqueIds.isEmpty()){
            duviceUniqueId=groupDeviceUniqueIds;
        }
        if(!getDeviceUniqueIds.isEmpty()&&!groupDeviceUniqueIds.isEmpty()){
            //获取交集
            duviceUniqueId = getDeviceUniqueIds.stream().filter(groupDeviceUniqueIds::contains).collect(Collectors.toList());
        }

        if(!duviceUniqueId.isEmpty()){
            groupWelcomeDeviceQuery.setDeviceUniqueIds(duviceUniqueId);
        }

        String orderBy = OrderByUtil.getOrderBy(groupWelcomeDeviceQuery.getOrderByField(), groupWelcomeDeviceQuery.isAsc());
        PageHelper.startPage(groupWelcomeDeviceQuery.getCurrent(),groupWelcomeDeviceQuery.getSize(),orderBy);

        List<GroupWelcomeDeviceVo> groupWelcomeDeviceVoList = groupWelcomeDeviceMapper.getGroupWelcomeDeviceList(groupWelcomeDeviceQuery);

        if(groupWelcomeDeviceVoList!=null&&!groupWelcomeDeviceVoList.isEmpty()){
            for (GroupWelcomeDeviceVo groupWelcomeDeviceVo:groupWelcomeDeviceVoList) {
                try {
                    WwDevice wwDevice = wwDeviceMapper.getById(groupWelcomeDeviceVo.getDeviceUniqueId(), groupWelcomeDeviceVo.getMerId());
                    if(wwDevice!=null){
                        groupWelcomeDeviceVo.setDeviceName(wwDevice.getDeviceName());
                        groupWelcomeDeviceVo.setHeadImgUrl(wwDevice.getHeadImgUrl());
                    }

                    if(!StringUtils.isBlank(groupWelcomeDeviceVo.getRule())){
                        groupWelcomeDeviceVo.setSleepRule(JSONObject.parseObject(groupWelcomeDeviceVo.getRule(), OperatorPlanDeviceRule.class));
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        return new MyPageInfo<>(groupWelcomeDeviceVoList);
    }

    @Override
    public Object getUsedDeviceUniqueIds(GroupWelcomeDto groupWelcomeDto) {
        if(groupWelcomeDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(groupWelcomeDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        GroupWelcome groupWelcome = groupWelcomeMapper.getById(groupWelcomeDto.getId(), groupWelcomeDto.getMerId());

        if(groupWelcome==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该方案不存在");
        }
        GroupWelcomeDeviceQuery groupWelcomeDeviceQuery=new GroupWelcomeDeviceQuery();
        groupWelcomeDeviceQuery.setMerId(groupWelcome.getMerId());
        groupWelcomeDeviceQuery.setPlanId(groupWelcome.getId());
        List<GroupWelcomeDeviceVo> groupWelcomeDeviceList = groupWelcomeDeviceMapper.getGroupWelcomeDeviceList(groupWelcomeDeviceQuery);


        if(groupWelcomeDeviceList!=null&&!groupWelcomeDeviceList.isEmpty()){
            List<Long> collect = groupWelcomeDeviceList.stream().map(GroupWelcomeDeviceVo::getDeviceUniqueId).distinct().collect(Collectors.toList());
            return collect;
        }else {
            return null;
        }
    }

    private Long getSixDigitsNum(){
        return  (long) ((Math.random() * 9 + 1) * 100000);
    }
}
